package com.imonsoft.sqm.validator.business.ipic_system;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.imonsoft.sqm.pojo.business.ipic_system.Claim;
import com.imonsoft.sqm.service.MessageUtil;

@Component("claimValidator")
public class ClaimValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return Claim.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "supplierId", "message.required.claim.supplier", "Supplier required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "partId", "message.required.claim.part", "Part required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "reporterCode", "message.required.claim.reporter", "Reporter required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "claimType", "message.required.claim.claim.type", "ClaimType required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "message.required.claim.start.date", "StartDate required!");
    }

    public void methodAddValidate(Object target, Errors errors){
        validate(target,errors);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "amountNotQualified", "message.required.claim.amount.not.qualified", "AmountNotQualified required!");
        Claim claim = (Claim) target;
        if(claim.getNotQualifiedReportCode().length()==(claim.getNotQualifiedReportCode().lastIndexOf("-")+1)){
            errors.rejectValue("notQualifiedReportCode", "message.required.not.qualified.report.code.flow.code");

        }
    }

    @Autowired
    private MessageUtil messageUtil;
    public List<String> getErrors(BindingResult result){
        List<String> errors = new ArrayList<String>();
        for (ObjectError error : result.getAllErrors()) {
            errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
        }
        return errors;
    }
}
